<?php


namespace App\Http\Controllers;


use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PageController extends Controller
{

    public function show(Request $request, $sqId){
       $data = $this->getDataBySqlId($sqId);
       $async = $request->get('async');
       if($async){
           $data['auto_sync'] = true;
       }
       $data['sq_id'] = $sqId;
       return view('preview', $data);
    }

    public function json($sqId){
        $data = $this->getDataBySqlId($sqId);
        $md5  = md5($data['data']);
        return self::success(['hash' => $md5, 'data' => json_decode($data['data'], true)]);
    }

    private function getDataBySqlId($sqId){
        $data = Cache::get('pub:'.$sqId);
        if(!$data) {
            throw new NotFoundHttpException();
        }
        return $data;
    }

    public function publishedList(Request $request){
        if(!$this->loginUserId){
            return self::success([]);
        }
        $this->validate($request, [
            'last_id' => 'required|integer'
        ]);
        $query = Page::whereUserId($this->loginUserId);
        $lastId = $request->get('last_id');
        if($lastId){
            $query = $query->where('id', '<', $lastId);
        }
        $pages = $query->orderBy('id','desc')->limit(20)->get();
        return self::success($pages);
    }

    public function delete(Request $request){
        if(!$this->loginUserId){
            return self::success([]);
        }
        $this->validate($request, [
            'id' => 'required|integer'
        ]);
        if (Page::whereUserId($this->loginUserId)->where('id', $request->get('id'))->delete()){
            return self::success('ok');
        }
        return self::error('删除失败, 请重试');
    }
}
